<template>
  <div class="chat-message" :class="messageClass">
    <!-- 用户消息 -->
    <div v-if="message.type === 'user'" class="message-user">
      <div class="message-content-wrapper">
        <!-- 消息内容 -->
        <div class="message-content">
          <!-- 文本内容 -->
          <div v-if="message.content" class="message-text">
            {{ message.content }}
          </div>

          <!-- 附件 -->
          <div
            v-if="message.attachments && message.attachments.length > 0"
            class="message-attachments"
          >
            <div
              v-for="attachment in message.attachments"
              :key="attachment.id"
              class="attachment-item"
              :class="`attachment-${attachment.type}`"
            >
              <!-- 图片附件 -->
              <div v-if="attachment.type === 'image'" class="attachment-image">
                <img
                  :src="attachment.url"
                  :alt="attachment.name"
                  class="attachment-image-content"
                  @click="handleImagePreview(attachment)"
                />
              </div>

              <!-- 文件附件 -->
              <div v-else class="attachment-file">
                <Icon
                  :name="getFileIcon(attachment)"
                  :size="20"
                  class="file-icon"
                />
                <div class="file-info">
                  <span class="file-name">{{ attachment.name }}</span>
                  <span class="file-size">{{
                    formatFileSize(attachment.size)
                  }}</span>
                </div>
                <Button
                  type="secondary"
                  variant="text"
                  icon="download"
                  size="small"
                  @click="handleDownload(attachment)"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 消息状态 -->
        <div v-if="message.status" class="message-status">
          <Icon
            v-if="message.status === 'sending'"
            name="clock"
            :size="12"
            class="status-icon status-sending"
          />
          <Icon
            v-else-if="message.status === 'sent'"
            name="check"
            :size="12"
            class="status-icon status-sent"
          />
          <Icon
            v-else-if="message.status === 'failed'"
            name="x"
            :size="12"
            class="status-icon status-failed"
          />
        </div>
      </div>

      <!-- 用户头像 -->
      <div v-if="showAvatar" class="message-avatar">
        <Icon name="user" :size="24" class="avatar-icon" />
      </div>
    </div>

    <!-- AI消息 -->
    <div v-else-if="message.type === 'assistant'" class="message-assistant">
      <!-- AI头像 -->
      <div v-if="showAvatar" class="message-avatar">
        <img
          v-if="currentPersona?.avatar"
          :src="currentPersona.avatar"
          :alt="currentPersona.name"
          class="avatar-image"
        />
        <Icon v-else name="bot" :size="24" class="avatar-icon" />
      </div>

      <div class="message-content-wrapper">
        <!-- 消息内容 -->
        <div class="message-content">
          <!-- 文本内容 -->
          <div v-if="message.content" class="message-text">
            <!-- Markdown渲染 -->
            <div
              v-if="isMarkdown(message.content)"
              class="message-markdown"
              v-html="renderMarkdown(message.content)"
            ></div>

            <!-- 普通文本 -->
            <div v-else class="message-plain-text">
              {{ message.content }}
            </div>
          </div>

          <!-- 生成的内容 -->
          <div
            v-if="message.metadata?.generatedContent"
            class="message-generated"
          >
            <!-- 图片生成 -->
            <div
              v-if="message.metadata.generatedContent.type === 'image'"
              class="generated-image"
            >
              <img
                :src="message.metadata.generatedContent.url"
                :alt="message.metadata.generatedContent.prompt"
                class="generated-image-content"
                @click="handleImagePreview(message.metadata.generatedContent)"
              />
              <p class="generated-prompt">
                {{ message.metadata.generatedContent.prompt }}
              </p>
            </div>

            <!-- 音频生成 -->
            <div
              v-else-if="message.metadata.generatedContent.type === 'audio'"
              class="generated-audio"
            >
              <audio
                :src="message.metadata.generatedContent.url"
                controls
                class="generated-audio-content"
              ></audio>
            </div>
          </div>
        </div>

        <!-- 消息操作 -->
        <div class="message-actions">
          <Button
            type="secondary"
            variant="text"
            icon="copy"
            size="small"
            @click="handleCopy"
            title="复制"
          />

          <Button
            v-if="message.status === 'failed'"
            type="secondary"
            variant="text"
            icon="refresh"
            size="small"
            @click="handleRetry"
            title="重试"
          />

          <Button
            type="secondary"
            variant="text"
            icon="thumbs-up"
            size="small"
            @click="handleLike"
            title="点赞"
          />

          <Button
            type="secondary"
            variant="text"
            icon="thumbs-down"
            size="small"
            @click="handleDislike"
            title="点踩"
          />
        </div>
      </div>
    </div>

    <!-- 系统消息 -->
    <div v-else-if="message.type === 'system'" class="message-system">
      <div class="system-content">
        <Icon name="info" :size="16" class="system-icon" />
        <span class="system-text">{{ message.content }}</span>
      </div>
    </div>

    <!-- 消息时间 -->
    <div v-if="showTime" class="message-time">
      {{ formatTime(message.timestamp) }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { marked } from "marked";
import Icon from "@/components/common/Icon.vue";
import Button from "@/components/common/Button.vue";

interface ChatMessage {
  id: string;
  type: "user" | "assistant" | "system";
  content: string;
  timestamp: number;
  status?: "sending" | "sent" | "failed";
  attachments?: any[];
  metadata?: Record<string, any>;
}

interface Persona {
  id: string;
  name: string;
  avatar?: string;
  description?: string;
}

interface Props {
  message: ChatMessage;
  currentPersona?: Persona;
  showAvatar?: boolean;
  showTime?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  showAvatar: true,
  showTime: true,
});

const emit = defineEmits<{
  retry: [messageId: string];
  copy: [content: string];
  delete: [messageId: string];
  like: [messageId: string];
  dislike: [messageId: string];
  imagePreview: [image: any];
  download: [attachment: any];
}>();

// 计算属性
const messageClass = computed(() => {
  return [
    `message-type-${props.message.type}`,
    {
      "message-failed": props.message.status === "failed",
      "message-sending": props.message.status === "sending",
    },
  ];
});

// 方法
const isMarkdown = (content: string): boolean => {
  // 简单检测是否包含Markdown语法
  const markdownPatterns = [
    /^#{1,6}\s+/m, // 标题
    /\*\*.*\*\*/, // 粗体
    /\*.*\*/, // 斜体
    /```[\s\S]*```/, // 代码块
    /`.*`/, // 行内代码
    /^\s*[-*+]\s+/m, // 列表
    /^\s*\d+\.\s+/m, // 有序列表
    /\[.*\]\(.*\)/, // 链接
  ];

  return markdownPatterns.some((pattern) => pattern.test(content));
};

const renderMarkdown = (content: string): string => {
  try {
    return marked(content, {
      breaks: true,
      gfm: true,
    });
  } catch (error) {
    console.error("Markdown渲染错误:", error);
    return content;
  }
};

const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1分钟
  if (diff < 60000) {
    return "刚刚";
  }

  // 小于1小时
  if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000);
    return `${minutes}分钟前`;
  }

  // 小于1天
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000);
    return `${hours}小时前`;
  }

  // 超过1天，显示具体时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });
  } else {
    return date.toLocaleString("zh-CN", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  }
};

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return "0 B";

  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

const getFileIcon = (attachment: any): string => {
  const ext = attachment.name.split(".").pop()?.toLowerCase();

  const iconMap: Record<string, string> = {
    pdf: "file-text",
    doc: "file-text",
    docx: "file-text",
    txt: "file-text",
    xls: "file-spreadsheet",
    xlsx: "file-spreadsheet",
    ppt: "file-presentation",
    pptx: "file-presentation",
    zip: "file-archive",
    rar: "file-archive",
    "7z": "file-archive",
    mp3: "file-audio",
    wav: "file-audio",
    mp4: "file-video",
    avi: "file-video",
    mov: "file-video",
  };

  return iconMap[ext || ""] || "file";
};

// 事件处理
const handleCopy = () => {
  emit("copy", props.message.content);
};

const handleRetry = () => {
  emit("retry", props.message.id);
};

const handleLike = () => {
  emit("like", props.message.id);
};

const handleDislike = () => {
  emit("dislike", props.message.id);
};

const handleImagePreview = (image: any) => {
  emit("imagePreview", image);
};

const handleDownload = (attachment: any) => {
  emit("download", attachment);
};
</script>

<style scoped>
/* 消息基础样式 */
.chat-message {
  margin-bottom: 16px;
}

/* 用户消息 */
.message-user {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  gap: 8px;
}

.message-user .message-content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  max-width: 70%;
}

.message-user .message-content {
  background-color: var(--primary-color);
  color: white;
  padding: 12px 16px;
  border-radius: 18px 18px 4px 18px;
  word-wrap: break-word;
  position: relative;
}

.message-user .message-text {
  line-height: 1.4;
}

/* AI消息 */
.message-assistant {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  gap: 8px;
}

.message-assistant .message-content-wrapper {
  display: flex;
  flex-direction: column;
  max-width: 70%;
  flex: 1;
}

.message-assistant .message-content {
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  padding: 12px 16px;
  border-radius: 18px 18px 18px 4px;
  word-wrap: break-word;
  position: relative;
}

.message-assistant .message-text {
  line-height: 1.5;
}

/* 系统消息 */
.message-system {
  display: flex;
  justify-content: center;
  margin: 8px 0;
}

.system-content {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background-color: var(--bg-tertiary);
  color: var(--text-secondary);
  border-radius: 12px;
  font-size: 12px;
}

.system-icon {
  color: var(--text-tertiary);
}

/* 头像 */
.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  background-color: var(--bg-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-icon {
  color: var(--text-tertiary);
}

/* 消息状态 */
.message-status {
  display: flex;
  align-items: center;
  margin-top: 4px;
  margin-right: 4px;
}

.status-icon {
  opacity: 0.6;
}

.status-sending {
  color: var(--warning-color);
  animation: pulse 1.5s ease-in-out infinite;
}

.status-sent {
  color: var(--success-color);
}

.status-failed {
  color: var(--error-color);
}

@keyframes pulse {
  0%,
  100% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
}

/* 消息操作 */
.message-actions {
  display: flex;
  gap: 4px;
  margin-top: 8px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.message-assistant:hover .message-actions {
  opacity: 1;
}

/* 消息时间 */
.message-time {
  text-align: center;
  font-size: 11px;
  color: var(--text-tertiary);
  margin-top: 4px;
}

/* 附件 */
.message-attachments {
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  border-radius: 8px;
  overflow: hidden;
}

/* 图片附件 */
.attachment-image {
  max-width: 300px;
  cursor: pointer;
}

.attachment-image-content {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 8px;
  transition: transform 0.2s ease;
}

.attachment-image-content:hover {
  transform: scale(1.02);
}

/* 文件附件 */
.attachment-file {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.message-assistant .attachment-file {
  background-color: var(--bg-tertiary);
  border-color: var(--border-color);
}

.file-icon {
  color: var(--text-secondary);
  flex-shrink: 0;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  display: block;
  font-size: 13px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  display: block;
  font-size: 11px;
  color: var(--text-tertiary);
  margin-top: 2px;
}

/* Markdown内容 */
.message-markdown {
  line-height: 1.6;
}

.message-markdown :deep(h1),
.message-markdown :deep(h2),
.message-markdown :deep(h3),
.message-markdown :deep(h4),
.message-markdown :deep(h5),
.message-markdown :deep(h6) {
  margin: 16px 0 8px;
  font-weight: 600;
}

.message-markdown :deep(h1) {
  font-size: 1.5em;
}
.message-markdown :deep(h2) {
  font-size: 1.3em;
}
.message-markdown :deep(h3) {
  font-size: 1.1em;
}

.message-markdown :deep(p) {
  margin: 8px 0;
}

.message-markdown :deep(ul),
.message-markdown :deep(ol) {
  margin: 8px 0;
  padding-left: 20px;
}

.message-markdown :deep(li) {
  margin: 4px 0;
}

.message-markdown :deep(code) {
  background-color: rgba(0, 0, 0, 0.1);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: "Courier New", monospace;
  font-size: 0.9em;
}

.message-markdown :deep(pre) {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 8px 0;
}

.message-markdown :deep(pre code) {
  background: none;
  padding: 0;
}

.message-markdown :deep(blockquote) {
  border-left: 3px solid var(--border-color);
  padding-left: 12px;
  margin: 8px 0;
  color: var(--text-secondary);
}

.message-markdown :deep(a) {
  color: var(--primary-color);
  text-decoration: none;
}

.message-markdown :deep(a:hover) {
  text-decoration: underline;
}

/* 生成内容 */
.message-generated {
  margin-top: 12px;
}

.generated-image {
  text-align: center;
}

.generated-image-content {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.generated-image-content:hover {
  transform: scale(1.02);
}

.generated-prompt {
  margin: 8px 0 0;
  font-size: 12px;
  color: var(--text-secondary);
  font-style: italic;
}

.generated-audio-content {
  width: 100%;
  max-width: 300px;
}

/* 失败状态 */
.message-failed .message-content {
  border: 1px solid var(--error-color);
  background-color: rgba(var(--error-color-rgb), 0.1);
}

/* 发送中状态 */
.message-sending .message-content {
  opacity: 0.7;
}

/* 响应式 */
@media (max-width: 768px) {
  .message-user .message-content-wrapper,
  .message-assistant .message-content-wrapper {
    max-width: 85%;
  }

  .message-content {
    padding: 10px 14px;
  }

  .attachment-image {
    max-width: 250px;
  }

  .message-avatar {
    width: 28px;
    height: 28px;
  }
}

@media (max-width: 480px) {
  .message-user .message-content-wrapper,
  .message-assistant .message-content-wrapper {
    max-width: 90%;
  }

  .message-content {
    padding: 8px 12px;
    font-size: 14px;
  }

  .attachment-image {
    max-width: 200px;
  }

  .message-avatar {
    width: 24px;
    height: 24px;
  }
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .message-markdown :deep(code) {
    background-color: rgba(255, 255, 255, 0.1);
  }

  .message-markdown :deep(pre) {
    background-color: rgba(255, 255, 255, 0.05);
  }
}

/* 无障碍支持 */
@media (prefers-reduced-motion: reduce) {
  .status-sending {
    animation: none;
  }

  .attachment-image-content,
  .generated-image-content {
    transition: none;
  }

  .attachment-image-content:hover,
  .generated-image-content:hover {
    transform: none;
  }
}
</style>
